﻿Imports Telerik.Web.Mvc

<Authorize()>
Public Class SociedadController
    Inherits BaseController

    Private ReadOnly repoSociedad_ As SociedadRepository

    Public Sub New(ByVal repoPediatraAsindo As PediatraAsindoRepository, ByVal saver As ContextSaver,
        ByVal repoSociedad As SociedadRepository)
        MyBase.New(repoPediatraAsindo, saver)
        repoSociedad_ = repoSociedad
    End Sub

    Private Function Sociedades() As GridModel(Of GridSociedadModel)
        Return New GridModel(Of GridSociedadModel)(repoSociedad_.All.OrderBy(Function(soc) soc.Nombre).ToList.MapListTo(Of GridSociedadModel)())
    End Function

    '
    ' GET: /Sociedad
    Function Lista() As ViewResult
        Return View(VistaLista, Sociedades)
    End Function

    <HttpPost()>
    <GridAction()>
    Public Function _Index() As ActionResult
        Return View(VistaLista, Sociedades)
    End Function

    <HttpPost()>
    <GridAction()>
    Public Function _Insert() As ActionResult
        Dim gridsoc As New GridSociedadModel
        If TryUpdateModel(gridsoc) Then
            Dim existente = repoSociedad_.All.SingleOrDefault(Function(socbd) socbd.Nombre = gridsoc.Nombre)
            If existente Is Nothing Then
                Dim soc = repoSociedad_.Create
                soc.Nombre = gridsoc.Nombre
                repoSociedad_.Add(soc, save:=True)
            End If
        End If
        Return View(VistaLista, Sociedades)
    End Function

    <HttpPost()>
    <GridAction()>
    Function _Edit(ByVal id As Integer, ByVal fc As FormCollection) As ActionResult
        Dim gridsoc As New GridSociedadModel
        If TryUpdateModel(gridsoc) Then
            Dim existente = repoSociedad_.All.SingleOrDefault(Function(soc) soc.Nombre = gridsoc.Nombre)
            If existente Is Nothing Then
                Dim soc = repoSociedad_.GetByID(id)
                soc.Nombre = gridsoc.Nombre
                Saver.Save()
            Else

            End If
        End If
        Return View(VistaLista, Sociedades)
    End Function

    <HttpPost()>
    <GridAction()>
    Function _Delete(ByVal id As Integer) As ActionResult
        repoSociedad_.DeleteById(id, save:=True)
        Return View(VistaLista, Sociedades)
    End Function

    Protected Overrides Sub CargarDatosComunes()
    End Sub

    Protected Overrides Function VistaFormulario() As String
        Return ""
    End Function

    Protected Overrides Function VistaLista() As String
        Return "ListaSociedades"
    End Function
End Class
